Problem Statement:

You are tasked with designing a system that calculates the total area of various geometric shapes. The system should adhere to the Open/Closed Principle from the SOLID principles, meaning that it should be open for extension but closed for modification. The goal is to allow the addition of new shapes without modifying the existing code that performs the area calculation.

Solution:

  1. Define a Shape Interface:

    public interface Shape {
        double calculateArea();
    }
  2. Implement Shapes:

    public class Rectangle implements Shape {
        private double width;
        private height;
    
        public Rectangle(double width, double height) {
            this.width = width;
            this.height = height;
        }
    
        @Override
        public double calculateArea() {
            return width * height;
        }
    }
    
    
    public class Circle implements Shape {
        private double radius;
    
        public Circle(double radius) {
            this.radius = radius;
        }
    
        @Override
        public double calculateArea() {
            return Math.PI * radius * radius;
        }
    }
  3. Create an AreaCalculator:

    public class AreaCalculator {
        public double calculateTotalArea(Shape[] shapes) {
            double totalArea = 0;
            for (Shape shape : shapes) {
                totalArea += shape.calculateArea();
            }
            return totalArea;
        }
    }
  4. Example Usage:

    public class Main {
        public static void main(String[] args) {
            Shape[] shapes = {
                    new Rectangle(5, 10),
                    new Circle(3),
                    // You can add more shapes without modifying existing code
                    // For example: new Triangle(base, height)
            };
    
            AreaCalculator areaCalculator = new AreaCalculator();
            double totalArea = areaCalculator.calculateTotalArea(shapes);
    
            System.out.println("Total Area: " + totalArea);
        }
    }